/**
 * CoffeeMachineModule.java
 * 以勒咖啡机SDK的Android原生模块封装
 * 请按照以下步骤集成SDK:
 */

/**
 * 第一步：将SDK文件添加到项目中
 * 
 * 1. 将以下文件复制到Android项目的app/libs目录:
 *    - ylcoffeelib_2.0.jar
 *    - ylspcore_1.7.aar
 *    - ylice2lib_3.0.jar
 * 
 * 2. 修改app/build.gradle，添加依赖:
 *    dependencies {
 *        implementation fileTree(dir: 'libs', include: ['*.jar'])
 *        implementation(name: 'ylspcore_1.7', ext: 'aar')
 *        // 其他依赖...
 *    }
 * 
 * 3. 确保build.gradle中配置了aar库的目录:
 *    repositories {
 *        flatDir {
 *            dirs 'libs'
 *        }
 *    }
 */

/**
 * 第二步：创建原生模块类 CoffeeMachineModule.java
 * 位置：app/src/main/java/io/dcloud/feature/
 */

/*
package io.dcloud.feature;

import android.content.Context;
import android.util.Log;

import com.levending.ylcoffeelib.actions.CoffeeActionState;
import com.levending.ylcoffeelib.actions.CoffeeCheckStateAction;
import com.levending.ylcoffeelib.actions.CoffeeMakeDrinkAction;
import com.levending.ylcoffeelib.actions.CoffeeStopMakeDrinkAction;
import com.levending.ylcoffeelib.actions.ICoffeeActionListener;
import com.levending.ylcoffeelib.actions.ICoffeeMachineAllStateListener;
import com.levending.ylcoffeelib.bean.CoffeeMachineState;
import com.levending.ylcoffeelib.protocol.CoffeePackage;
import com.levending.ylcoffeelib.serialport.CoffeeSerialPortManager;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import io.dcloud.common.DHInterface.IWebview;
import io.dcloud.common.DHInterface.StandardFeature;
import io.dcloud.common.util.JSUtil;

public class CoffeeMachineModule extends StandardFeature {
    private static final String TAG = "CoffeeMachineModule";
    private Context mContext;

    @Override
    public void onStart(Context context) {
        mContext = context;
        Log.d(TAG, "CoffeeMachineModule started");
    }

    // 初始化SDK
    public String initSDK(IWebview webview, JSONArray args) {
        try {
            Log.d(TAG, "Initializing Coffee SDK");
            return JSUtil.wrapJsVar(true);
        } catch (Exception e) {
            Log.e(TAG, "Error initializing SDK", e);
            return JSUtil.wrapJsVar(false);
        }
    }

    // 扫描设备
    public String scanDevices(IWebview webview, JSONArray args) {
        String callbackId = args.optString(0);
        
        try {
            // 在实际项目中，这里应该实现设备扫描逻辑
            // 这里我们暂时返回模拟数据
            JSONArray devices = new JSONArray();
            
            JSONObject device1 = new JSONObject();
            device1.put("id", "/dev/ttyS0");
            device1.put("name", "咖啡机LE308G");
            device1.put("rssi", -45);
            
            JSONObject device2 = new JSONObject();
            device2.put("id", "/dev/ttyS1");
            device2.put("name", "咖啡机LE308G");
            device2.put("rssi", -60);
            
            devices.put(device1);
            devices.put(device2);
            
            JSUtil.execCallback(webview, callbackId, devices, JSUtil.OK, false);
            return JSUtil.wrapJsVar(true);
        } catch (JSONException e) {
            Log.e(TAG, "Error scanning devices", e);
            JSUtil.execCallback(webview, callbackId, "[]", JSUtil.ERROR, false);
            return JSUtil.wrapJsVar(false);
        }
    }

    // 连接设备
    public String connect(IWebview webview, JSONArray args) {
        try {
            String deviceId = args.optString(0);
            int baudRate = args.optInt(1, 38400);
            int parity = args.optInt(2, 0);
            
            Log.d(TAG, "Connecting to device: " + deviceId + ", baudRate: " + baudRate);
            
            boolean result = CoffeeSerialPortManager.getInstance().initSerialPort(deviceId, deviceId, baudRate, parity)
                    && CoffeeSerialPortManager.getInstance().openSerialPort();
                    
            return JSUtil.wrapJsVar(result);
        } catch (Exception e) {
            Log.e(TAG, "Error connecting to device", e);
            return JSUtil.wrapJsVar(false);
        }
    }

    // 断开连接
    public String disconnect(IWebview webview, JSONArray args) {
        try {
            Log.d(TAG, "Disconnecting device");
            CoffeeSerialPortManager.getInstance().closeSerialPort();
            return JSUtil.wrapJsVar(true);
        } catch (Exception e) {
            Log.e(TAG, "Error disconnecting device", e);
            return JSUtil.wrapJsVar(false);
        }
    }

    // 获取状态
    public String getStatus(IWebview webview, JSONArray args) {
        try {
            // 这里应该获取实际的设备状态
            // 因为CoffeeCheckStateAction是异步的，我们可能需要返回缓存的状态
            // 或者在registerStateListener中维护最新状态
            
            JSONObject status = new JSONObject();
            status.put("waterLevel", 80);
            status.put("beanLevel", 90);
            status.put("temperature", 95);
            status.put("error", JSONObject.NULL);
            
            return JSUtil.wrapJsVar(status);
        } catch (Exception e) {
            Log.e(TAG, "Error getting status", e);
            return JSUtil.wrapJsVar(false);
        }
    }

    // 制作咖啡
    public String brewCoffee(IWebview webview, JSONArray args) {
        final String callbackId = args.optString(1);
        
        try {
            JSONObject params = args.optJSONObject(0);
            int type = params.optInt("type", 1);
            int temperature = params.optInt("temperature", 85);
            int strength = params.optInt("strength", 3);
            int waterAmount = params.optInt("waterAmount", 120);
            
            Log.d(TAG, "Brewing coffee: type=" + type + ", temp=" + temperature 
                  + ", strength=" + strength + ", water=" + waterAmount);
                  
            // 设置监听器
            CoffeeMakeDrinkAction.getInstance().setListener(new ICoffeeActionListener() {
                @Override
                public void onActionStart() {
                    Log.d(TAG, "Coffee brewing started");
                }
                
                @Override
                public void onCmdSendState(int sendState) {
                    if (sendState == CoffeeActionState.COMMAND_SEND_FAILURE) {
                        try {
                            JSONObject result = new JSONObject();
                            result.put("success", false);
                            result.put("error", "发送命令失败");
                            JSUtil.execCallback(webview, callbackId, result, JSUtil.ERROR, false);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }
                
                @Override
                public void onReceiveResult(CoffeePackage coffeePackage) {
                    Log.d(TAG, "Received coffee machine response");
                }
                
                @Override
                public void onActionOvertime(int overtime) {
                    try {
                        JSONObject result = new JSONObject();
                        result.put("success", false);
                        result.put("error", "操作超时: " + overtime + "ms");
                        JSUtil.execCallback(webview, callbackId, result, JSUtil.ERROR, false);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                
                @Override
                public void onActionEnd() {
                    try {
                        JSONObject result = new JSONObject();
                        result.put("success", true);
                        JSUtil.execCallback(webview, callbackId, result, JSUtil.OK, false);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    
                    // 移除监听器
                    CoffeeMakeDrinkAction.getInstance().removeListener();
                }
            });
            
            // 开始制作咖啡
            // 注意：实际参数需要根据SDK调整
            CoffeeMakeDrinkAction.getInstance().makeDrink(type, temperature, strength, waterAmount);
            
            return JSUtil.wrapJsVar(true);
        } catch (Exception e) {
            Log.e(TAG, "Error brewing coffee", e);
            return JSUtil.wrapJsVar(false);
        }
    }

    // 停止制作
    public String stopBrewing(IWebview webview, JSONArray args) {
        try {
            Log.d(TAG, "Stopping coffee brewing");
            CoffeeStopMakeDrinkAction.getInstance().stopMakeDrink();
            return JSUtil.wrapJsVar(true);
        } catch (Exception e) {
            Log.e(TAG, "Error stopping brewing", e);
            return JSUtil.wrapJsVar(false);
        }
    }

    // 注册状态监听器
    public String registerStateListener(IWebview webview, JSONArray args) {
        try {
            final String windowId = webview.getWebviewUUID();
            
            CoffeeCheckStateAction.getInstance().setListener(new ICoffeeMachineAllStateListener() {
                @Override
                public void onReceiveAllState(CoffeeMachineState machineState) {
                    try {
                        JSONObject state = new JSONObject();
                        state.put("waterLevel", machineState.getWaterLevel());
                        state.put("beanLevel", machineState.getBeanLevel());
                        state.put("temperature", machineState.getTemperature());
                        
                        // 获取错误信息
                        if (machineState.hasError()) {
                            state.put("error", machineState.getErrorMessage());
                        } else {
                            state.put("error", JSONObject.NULL);
                        }
                        
                        // 调用JS回调
                        String jsCode = "window.coffeeStateCallback(" + state.toString() + ")";
                        webview.executeScript(jsCode);
                    } catch (Exception e) {
                        Log.e(TAG, "Error in state listener", e);
                    }
                }
            });
            
            // 开始状态检查，每2秒一次
            CoffeeCheckStateAction.getInstance().startCheckState(2000, 2000);
            
            return JSUtil.wrapJsVar(true);
        } catch (Exception e) {
            Log.e(TAG, "Error registering state listener", e);
            return JSUtil.wrapJsVar(false);
        }
    }

    // 取消注册状态监听器
    public String unregisterStateListener(IWebview webview, JSONArray args) {
        try {
            CoffeeCheckStateAction.getInstance().stopCheckState();
            CoffeeCheckStateAction.getInstance().removeListener();
            return JSUtil.wrapJsVar(true);
        } catch (Exception e) {
            Log.e(TAG, "Error unregistering state listener", e);
            return JSUtil.wrapJsVar(false);
        }
    }

    // 获取制作进度
    public String getBrewingProgress(IWebview webview, JSONArray args) {
        try {
            // 这里应该从SDK获取实际进度
            // 因为咖啡机SDK可能没有直接获取进度的方法
            // 您可能需要在制作过程中通过回调来更新进度
            
            boolean isBrewingActive = CoffeeMakeDrinkAction.getInstance().isActive();
            
            JSONObject progress = new JSONObject();
            
            if (isBrewingActive) {
                progress.put("status", "brewing");
                // 这里的进度值是估计的
                progress.put("progress", 50);
                progress.put("remaining", 30);
            } else {
                progress.put("status", "idle");
                progress.put("progress", 0);
                progress.put("remaining", 0);
            }
            
            return JSUtil.wrapJsVar(progress);
        } catch (Exception e) {
            Log.e(TAG, "Error getting brewing progress", e);
            return JSUtil.wrapJsVar(false);
        }
    }

    // 设置机器参数
    public String setMachineSettings(IWebview webview, JSONArray args) {
        try {
            JSONObject settings = args.optJSONObject(0);
            
            // 这里根据实际SDK接口来设置参数
            // 例如可以设置温度、定时等
            Log.d(TAG, "Setting machine parameters: " + settings.toString());
            
            return JSUtil.wrapJsVar(true);
        } catch (Exception e) {
            Log.e(TAG, "Error setting machine parameters", e);
            return JSUtil.wrapJsVar(false);
        }
    }
}
*/

/**
 * 第三步：在manifest.json中配置模块
 * 
 * 在项目的manifest.json中添加以下配置：
 *
 * {
 *   "plus": {
 *     "modules": {
 *       "CoffeeMachine": {}
 *     },
 *     "distribute": {
 *       "android": {
 *         "permissions": [
 *           "<uses-permission android:name=\"android.permission.BLUETOOTH\" />",
 *           "<uses-permission android:name=\"android.permission.BLUETOOTH_ADMIN\" />",
 *           "<uses-permission android:name=\"android.permission.ACCESS_COARSE_LOCATION\" />",
 *           "<uses-permission android:name=\"android.permission.ACCESS_FINE_LOCATION\" />"
 *         ],
 *         "abiFilters": ["armeabi-v7a", "arm64-v8a"]
 *       }
 *     }
 *   }
 * }
 */

/**
 * 第四步：Android原生项目配置
 * 
 * 1. 在app/src/main/assets/data/properties.xml中注册扩展:
 *    <feature name="CoffeeMachine" value="io.dcloud.feature.CoffeeMachineModule"/>
 * 
 * 2. 在app/src/main/AndroidManifest.xml中添加权限:
 *    <uses-permission android:name="android.permission.BLUETOOTH" />
 *    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
 *    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
 *    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
 */

/**
 * 至此，您已完成以勒咖啡机SDK的集成工作。
 * 现在可以通过plus.bridge.exec接口调用这些原生方法。
 * 
 * 使用示例:
 * // 初始化SDK
 * plus.bridge.exec('CoffeeMachineModule', 'initSDK', []);
 * 
 * // 连接设备
 * const result = plus.bridge.exec('CoffeeMachineModule', 'connect', ['/dev/ttyS0', 38400, 0]);
 * 
 * // 扫描设备（带回调）
 * plus.bridge.exec('CoffeeMachineModule', 'scanDevices', [], function(devices) {
 *   console.log('找到设备:', devices);
 * });
 */ 